package com.blog4j.contentVerify.processor;

import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.ImageModerationRequest;
import com.aliyun.green20220302.models.ImageModerationResponse;
import com.aliyun.green20220302.models.ImageModerationResponseBody;
import com.aliyun.green20220302.models.TextModerationRequest;
import com.aliyun.green20220302.models.TextModerationResponse;
import com.aliyun.green20220302.models.TextModerationResponseBody;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.blog4j.contentVerify.constants.VerifyConstants;
import com.blog4j.contentVerify.context.ContentVerifyContext;
import com.blog4j.contentVerify.context.VerifyResult;
import com.blog4j.contentVerify.enums.VerifyResultEnum;
import com.blog4j.contentVerify.exception.ContentVerifyException;
import com.blog4j.contentVerify.model.ImageVerifyModel;
import com.blog4j.contentVerify.model.TextVerifyModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import java.util.List;
import java.util.UUID;

/**
 * @author 98k灬
 * @version v1.0.0
 * @Description : 功能描述
 * @Create on : 2024/9/2 21:03
 **/
@Slf4j
public class VerifyProcessorImpl extends AbstractVerifyProcessor {
    @Override
    protected void doTextVerify(ContentVerifyContext verifyContext) {
        Client client = verifyContext.getClient();
        TextVerifyModel textVerifyModel = verifyContext.getTextVerifyModel();
        // 构建请求参数
        TextModerationRequest textModerationRequest = buildTextRequestParam(textVerifyModel);
        VerifyResult verifyResult = new VerifyResult();
        try {
            TextModerationResponse response = client.textModerationWithOptions(textModerationRequest, new RuntimeOptions());
            Integer statusCode = response.getStatusCode();
            if (statusCode != HttpStatus.HTTP_OK) {
                verifyResult.setStatus(Boolean.FALSE);
                verifyContext.setVerifyResult(verifyResult);
                return;
            }
            TextModerationResponseBody responseBody = response.getBody();
            Integer code = responseBody.getCode();
            if (code != HttpStatus.HTTP_OK) {
                verifyResult.setStatus(Boolean.FALSE);
                verifyContext.setVerifyResult(verifyResult);
                return;
            }
            TextModerationResponseBody.TextModerationResponseBodyData data = responseBody.getData();
            String labels = data.getLabels();
            String reason = data.getReason();
            if (StringUtils.isBlank(labels) && StringUtils.isBlank(reason)) {
                log.info("verify pass");
                verifyContext.setVerifyResult(verifyResult);
                return;
            }

            log.info("labels: [{}], reason: [{}]", labels, reason);
            verifyResult.setResult(VerifyResultEnum.REJECT);
            if (StringUtils.isNotBlank(labels)) {
                verifyResult.setLabels(labels);
            }
            if (StringUtils.isNotBlank(reason)) {
                JSONObject reasonJsonObj = JSONObject.parseObject(reason);
                String riskLevel = reasonJsonObj.getString(VerifyConstants.RISK_LEVEL);
                String riskTips = reasonJsonObj.getString(VerifyConstants.RISK_TIPS);
                String riskWords = reasonJsonObj.getString(VerifyConstants.RISK_WORDS);
                verifyResult.setRiskLevel(riskLevel);
                verifyResult.setRiskTips(riskTips);
                verifyResult.setRiskWords(riskWords);
            }
            verifyContext.setVerifyResult(verifyResult);
        } catch (TeaException error) {
            log.error("TeaException: [{}]", error.getMessage());
            log.error("Recommend: [{}]", error.getData().get("Recommend"));
        } catch (Exception _error) {
            log.error("TeaException: [{}]", _error.getMessage());
        }
    }

    @Override
    protected void doImageVerify(ContentVerifyContext verifyContext) {
        Client client = verifyContext.getClient();
        ImageVerifyModel imageVerifyModel = verifyContext.getImageVerifyModel();
        // 构建请求参数
        ImageModerationRequest request = buildImageRequestParam(imageVerifyModel);
        ImageModerationResponse response;
        VerifyResult verifyResult = new VerifyResult();
        try {
            response = client.imageModerationWithOptions(request, new RuntimeOptions());
            if (response.getStatusCode() != HttpStatus.HTTP_OK) {
                verifyResult.setStatus(Boolean.FALSE);
                verifyContext.setVerifyResult(verifyResult);
                return;
            }

            ImageModerationResponseBody body = response.getBody();
            log.info("requestId: [{}], code: [{}], msg: [{}]", body.getRequestId(), body.getCode(), body.getMsg());
            if (body.getCode() != HttpStatus.HTTP_OK) {
                verifyResult.setStatus(Boolean.FALSE);
                verifyContext.setVerifyResult(verifyResult);
                return;
            }

            ImageModerationResponseBody.ImageModerationResponseBodyData data = body.getData();
            log.info("dataId: [{}]", data.getDataId());
            String riskLevel = data.getRiskLevel();
            if (StringUtils.equalsIgnoreCase(riskLevel, VerifyConstants.RISK_LEVEL_NONE)) {
                log.info("verify success");
                verifyContext.setVerifyResult(verifyResult);
                return;
            }
            List<ImageModerationResponseBody.ImageModerationResponseBodyDataResult> results = data.getResult();
            log.info("results: [{}]", JSON.toJSONString(results));
            StringBuilder labelSb = new StringBuilder();
            StringBuilder descSb = new StringBuilder();
            for (ImageModerationResponseBody.ImageModerationResponseBodyDataResult result : results) {
                labelSb.append(result.getLabel()).append(VerifyConstants.COMMA);
                descSb.append(result.getDescription()).append(VerifyConstants.COMMA);
            }

            if (labelSb.charAt(labelSb.length() - 1) == ',') {
                labelSb.deleteCharAt(labelSb.length() - 1);
            }
            if (descSb.charAt(descSb.length() - 1) == ',') {
                descSb.deleteCharAt(descSb.length() - 1);
            }
            log.info("label: [{}], desc: [{}]", labelSb, descSb);
            verifyResult.setLabels(labelSb.toString())
                    .setRiskLevel(riskLevel)
                    .setRiskTips(descSb.toString())
                    .setResult(VerifyResultEnum.REJECT);
            verifyContext.setVerifyResult(verifyResult);
        } catch (Exception exception) {
            log.error("图片审核出现异常");
            throw new ContentVerifyException("图片审核出现异常");
        }
    }

    // ------------------------------ private -------------------------------------------

    private TextModerationRequest buildTextRequestParam(TextVerifyModel textVerifyModel) {
        JSONObject jsonObj = new JSONObject();
        jsonObj.put(VerifyConstants.VERIFY_TEXT_CONTENT, textVerifyModel.getTextContent());
        return new TextModerationRequest()
                .setService(textVerifyModel.getTextService())
                .setServiceParameters(jsonObj.toJSONString());
    }

    private ImageModerationRequest buildImageRequestParam(ImageVerifyModel imageVerifyModel) {
        JSONObject jsonObj = new JSONObject();
        jsonObj.put(VerifyConstants.IMAGE_URL, imageVerifyModel.getImageUrl());
        jsonObj.put(VerifyConstants.DATA_ID, UUID.randomUUID().toString());
        ImageModerationRequest request = new ImageModerationRequest();
        request.setService(VerifyConstants.BASE_LINE_CHECK);
        request.setServiceParameters(jsonObj.toJSONString());
        return request;
    }
}
